'use client';
// 客户端渲染的组件中使用
import { useEffect, useState } from 'react';
import i18next from 'i18next';
import { initReactI18next, useTranslation as useTranslationOrg } from 'react-i18next';
import { useCookies } from 'react-cookie';
import resourcesToBackend from 'i18next-resources-to-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
// import { getOptions, i18nSettings } from './settings';
// import { IS_SSR } from '@/config/env';

i18next
  .use(initReactI18next)
  .use(LanguageDetector)
  .use(
    resourcesToBackend(
      (language: string, namespace: string) => import(`./${language}/${namespace}.json`),
    ),
  )
  .init({
    // ...getOptions(),
    lng: undefined, // let detect the language on client side
    detection: {
      order: ['path', 'htmlTag', 'cookie', 'navigator'],
    },
    // preload: IS_SSR ? i18nSettings.locales : [],
  });

/**
 * 客户端渲染的组件中使用
 */
export function useTranslation(lng: string, ns: string | string[] = '', options: any = {}) {
  // const namespace = ns ? ns : i18nSettings.defaultNS;
  // const [cookies, setCookie] = useCookies([i18nSettings.cookieName]);
  const ret = useTranslationOrg(ns, options);
  const { i18n } = ret;

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [activeLng, setActiveLng] = useState(i18n.resolvedLanguage);
  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    if (activeLng === i18n.resolvedLanguage) return;
    setActiveLng(i18n.resolvedLanguage);
  }, [activeLng, i18n.resolvedLanguage]);
  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    if (!lng || i18n.resolvedLanguage === lng) return;
    i18n.changeLanguage(lng);
  }, [lng, i18n]);
  // eslint-disable-next-line react-hooks/rules-of-hooks
  return ret;
}